package com.qf.jie.controller.servlet;



import com.alibaba.fastjson.JSON;
import com.qf.jie.entity.vo.RespBean;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.处理 post 提交方式的乱码问题
        request.setCharacterEncoding("utf-8");
        //2.处理响应乱码问题
        response.setContentType("text/html;charset=utf-8");
        //3.获取 type 值
        String type = request.getParameter("type");
        //4.获取当前 Servlet 的反射对象
        Class<? extends BaseServlet> clazz = this.getClass();
        try {
            //5.通过反射对象和 type 值获取方法对象
            Method method = clazz.getDeclaredMethod(type, HttpServletRequest.class, HttpServletResponse.class);
            //6.打开权限
            method.setAccessible(true);
            //7.调用方法获取响应对象
            RespBean respBean = (RespBean)method.invoke(this, request, response);
            //8.响应前端
            if(respBean != null){
                response.getWriter().write(JSON.toJSONString(respBean));
            }
        } catch (Exception e/*NoSuchMethodException | IllegalAccessException | InvocationTargetException e*/) {
            response.getWriter().write( "请求异常, type=" + type);
            e.printStackTrace();
        }
    }
}
